// 封装一层 axios
import axios from 'axios'
import qs from 'qs'

axios.defaults.timeout = 15000
axios.defaults.withCredentials = false
axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'

// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    // eslint-disable-next-line no-console
    if (config.method === 'post' && (config.url.includes('weapi') || config.url.includes('vipapi'))) {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      config.data = qs.stringify(config.data)
    }
    return config
  },
  (error) => {
    return Promise.error(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  (res) => {
    return Promise.resolve(res)
  },
  (error) => {
    if (error && error.response) {
      // 处理正常请求返回的异常
      const status = error.response.status
      // eslint-disable-next-line no-console
      console.log('异常status: ' + status)
    }
    if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
      // 请求超时处理
      // eslint-disable-next-line no-console
      console.log('请求超时')
      try {
        this.$toast('请求超时')
      } catch (error) { }
    }
    return Promise.reject(error)
  }
)

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
// eslint-disable-next-line no-empty-pattern
export function get (url, params = null) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params })
      .then((res) => {
        resolve(res)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post (url, data) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then((res) => {
        resolve(res)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

/**
 * delete方法，对应delete请求
 * @param {String} url [请求的url地址]
 */
export function _delete (url) {
  return new Promise((resolve, reject) => {
    axios.delete(url)
      .then((res) => {
        resolve(res)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
